#include <QLabel>
#include <QLineEdit>
#include <QToolButton>
#include <QHBoxLayout>
#include <QPushButton>
#include <QUrl>
#include <QFileInfo>
#include <QDebug>

#include "searchbar.h"

namespace Jcr
{
class SearchBarPrivate
{
public:
    QLineEdit* urlEdit;
    QPushButton* goButton;
    QPushButton* showButton;
    QPushButton* downloadButton;
};

SearchBar::SearchBar(QWidget *parent) : QWidget(parent)
{
    d_ptr = new SearchBarPrivate;

    QHBoxLayout* layout = new QHBoxLayout;
    QLabel* promptLabel = new QLabel(tr("Url: "), this);
    layout->addWidget(promptLabel);
    d_ptr->urlEdit = new QLineEdit(this);
    d_ptr->urlEdit->setClearButtonEnabled(true);
    d_ptr->urlEdit->setText("http://news.163.com/photoview/00AP0001/109004.html#p=BE0H3ARK00AP0001");
    layout->addWidget(d_ptr->urlEdit);

    d_ptr->goButton = new QPushButton(tr("Go"), this);
    d_ptr->showButton = new QPushButton(tr("Show"), this);
    d_ptr->showButton->setToolTip(tr("Show Download Center"));
    d_ptr->showButton->setChecked(true);
    d_ptr->showButton->setCheckable(true);

    d_ptr->downloadButton = new QPushButton(tr("Download"), this);
    d_ptr->downloadButton->setEnabled(false);

    layout->addWidget(d_ptr->goButton);
    layout->addWidget(d_ptr->downloadButton);
    layout->addWidget(d_ptr->showButton);
    setLayout(layout);

    connect(d_ptr->goButton, SIGNAL(clicked(bool)), this, SLOT(onButtonClicked(bool)));
    connect(d_ptr->showButton, SIGNAL(clicked(bool)), this, SLOT(onButtonClicked(bool)));
    connect(d_ptr->downloadButton, SIGNAL(clicked(bool)), this, SLOT(onButtonClicked(bool)));
    connect(d_ptr->urlEdit, SIGNAL(returnPressed()), this, SLOT(onEditReturnPressed()));
}

SearchBar::~SearchBar()
{
    delete d_ptr;
}

void SearchBar::onDownloadEnabled(bool enabled)
{
    d_ptr->downloadButton->setEnabled(enabled);
}

void SearchBar::onButtonClicked(bool check)
{
    QPushButton* pb = qobject_cast<QPushButton*>(sender());

    if (pb == d_ptr->goButton) {
        const QString text = d_ptr->urlEdit->text();
        if (!text.isEmpty()) {
            QFileInfo f(text);
            int extLen = f.suffix().length();
            if (extLen <= 3)
                emit downloadUrl(QUrl(text));
            else
                emit parseUrl(QUrl(text));

        }
    } else if (pb == d_ptr->showButton) {
        emit setDownloadCenterVisible(check);
    } else if (pb == d_ptr->downloadButton) {
        emit downloadSelectedItems();
    }
}

void SearchBar::onEditReturnPressed()
{
    const QString text = d_ptr->urlEdit->text();
    if (!text.isEmpty())
        emit downloadUrl(QUrl(text));
}

} // namespace jcr
